package org.feng.utils;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import org.feng.base.constant.Constant;
import org.feng.base.constant.RedisConstant;
import org.feng.entity.User;
import org.feng.utils.redis.RedisString;

/**
 * @author by feng
 * @des 用户工具类
 * @date 2021/4/27 14:03
 */
public class UserUtil {
    /**
     * 获取用户id
     *
     * @return
     */
    public static Long getUserId() {
        Long userId = StpUtil.getLoginIdAsLong();
        Assert.notNull(userId, "用户信息获取失败");
        return userId;
    }

    /**
     * 获取部门id
     * @return
     */
    public static Long getUserDeptId() {
        User user = getUser();
        return user.getDeptId();
    }
    /**
     * 获取租户id
     * @return
     */
    public static Long getTenantId() {
        try {
            StpUtil.checkLogin();
        } catch (Exception e) {
           return null;
        }
        User user = getUser();
        return user.getTenantId();
    }

    /**
     * 获取用户对象
     * @return
     */
    public static User getUser() {
        StpUtil.checkLogin();
        RedisString redisString = SpringUtil.getBean(RedisString.class);
        Object userObj = redisString.get(RedisConstant.USER_INFO_PREFIX + getUserId());
        Assert.notNull(userObj, "用户信息获取失败");
        return JSON.parseObject(JSON.parse(userObj.toString()).toString(),User.class);
    }
}
